package com.doubleview.sandbox;

import groovy.lang.GroovyShell;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.junit.Test;
import org.kohsuke.groovy.sandbox.GroovyInterceptor;
import org.kohsuke.groovy.sandbox.SandboxTransformer;

/**
 * @author huchengchao <huchengchao@kuaishou.com>
 * Created on 2022-03-15
 */
public class GroovyTest {


    @Test
    public void sandboxRun() {
        final GroovyShell sh = new GroovyShell(new CompilerConfiguration()
                .addCompilationCustomizers(new SandboxTransformer()));
        new NoSystemExitSandbox().register();
        new NoRunTimeSandbox().register();
        sh.parse("System.exit(0)").run();
    }


    class NoSystemExitSandbox extends GroovyInterceptor {
        @Override
        public Object onStaticCall(GroovyInterceptor.Invoker invoker, Class receiver, String method, Object... args) throws Throwable {
            if (receiver == System.class && method == "exit")
                throw new SecurityException("No call on System.exit() please");
            return super.onStaticCall(invoker, receiver, method, args);
        }
    }

    class NoRunTimeSandbox extends GroovyInterceptor {
        @Override
        public Object onStaticCall(GroovyInterceptor.Invoker invoker, Class receiver, String method, Object... args) throws Throwable {
            if (receiver == Runtime.class)
                throw new SecurityException("No call on RunTime please");
            return super.onStaticCall(invoker, receiver, method, args);
        }
    }

}
